package com.ssd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssd.entity.GiftExchange;
import com.ssd.entity.dto.request.GiftExchangePutReqDTO;
import com.ssd.entity.dto.request.GiftExchangeQueryForPageReqDTO;
import com.ssd.mapper.GiftExchangeMapper;
import com.ssd.service.IGiftExchangeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssd.utils.UserContext;
import com.ssd.viewmodel.Pager;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 礼品兑换表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-21
 */
@Service
public class GiftExchangeServiceImpl extends ServiceImpl<GiftExchangeMapper, GiftExchange> implements IGiftExchangeService {

    @Override
    public List<GiftExchange> queryGiftExchangeList(Long lastId) {
        //1.获取用户id
        Long userId = UserContext.currentUserId();
        return lambdaQuery()
                .eq(GiftExchange::getUserId, userId)//条件：用户id
                .lt(ObjectUtil.isNotNull(lastId), GiftExchange::getId, lastId)//条件（如果有）：小于lastId
                .orderByDesc(GiftExchange::getId)//按id降序排列
                .last(" limit 10")//只查10条
                .list();
    }

    @Override
    public void setExchangeInfo(GiftExchangePutReqDTO giftExchangePutReqDTO) {
        //1.拷贝
        GiftExchange bean = BeanUtil.toBean(giftExchangePutReqDTO, GiftExchange.class);
        updateById(bean);
    }

    @Override
    public Pager<GiftExchange> queryOperationGiftExchangeList(GiftExchangeQueryForPageReqDTO giftExchangeQueryForPageReqDTO) {
        //1.设置分页参数
        Page<GiftExchange> giftExchangePage = new Page<>(giftExchangeQueryForPageReqDTO.getPageNum(), giftExchangeQueryForPageReqDTO.getPageSize());
        //2.设置查询条件
        Page<GiftExchange> page = lambdaQuery()
                //活动编号
                .eq(GiftExchange::getGiftId, giftExchangeQueryForPageReqDTO.getGiftId())
                //用户编号
                .eq(ObjectUtil.isNotNull(giftExchangeQueryForPageReqDTO.getUserId()), GiftExchange::getUserId, giftExchangeQueryForPageReqDTO.getUserId())
                //快递状态
                .eq(ObjectUtil.isNotNull(giftExchangeQueryForPageReqDTO.getStatus()), GiftExchange::getStatus, giftExchangeQueryForPageReqDTO.getStatus())
                //模糊查询
                .orderByDesc(GiftExchange::getCreateTime)//按id降序排列
                .page(giftExchangePage);

        return Pager.build(page);
    }

    @Override
    public void confirmReceipt(Long id) {
        //1.获取用户信息
        Long userId = UserContext.currentUserId();
        //2.更新状态为已完成
        boolean update = lambdaUpdate().eq(GiftExchange::getId, id)
                .eq(GiftExchange::getUserId, userId)
                .set(GiftExchange::getStatus, 3)
                .update();
        if (!update){
            throw new RuntimeException("确认收货失败！");
        }
    }
}
